package com.hundsun.fcp.fragments;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.hundsun.fcp.R;
import com.hundsun.fcp.activity.MainActivity;
import com.hundsun.fcp.adapter.IconAdapter;
import com.hundsun.fcp.base.BaseFragment;
import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.openapi.IOpenApiDataServiceCallback;
import com.hundsun.fcp.openapi.trade.TradeBannerDataService;
import com.hundsun.fcp.openapi.trade.bean.ResponseBannerBean;
import com.umeng.analytics.MobclickAgent;

public class IndexFragments extends BaseFragment{
	
	private Logger logger = AndroidLogger.getLogger() ;
	private AtomicBoolean VIEWPAGER_ONTOUCH = new AtomicBoolean(false);
	private Runnable UpdateVp;
	private Handler handler = new Handler();
	private IconAdapter mViewPagerAdapter;
	
	private View mRootView ;
	private ViewPager mViewPager ;
	private IconAdapter mIconAdapter ;
	private ImageView[] mDotImageViews;
	private ViewGroup mDotLayout;
	
	private View mErrorView ;
	/**开始赚钱按钮*/
	private Button mStartMoneyBtn ;
	/**产品名称*/
	private TextView mNameTv ;
	/**收益率*/
	private TextView mIncomeTv ;
	
	private TradeBannerDataService mBannerService ;
	
	private MainActivity mActivity ;
	 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(mRootView==null){
			mRootView = inflater.inflate(R.layout.fragment_index, container, false) ;
			initHeaderView() ;
			initView() ;
		}
		
		return mRootView;
	}
	
	private void initHeaderView() {
		mBannerService = new TradeBannerDataService(getActivity()) ;
		mBannerService.setCallback(mBannerCallback) ;
		mViewPager = (ViewPager) mRootView.findViewById(R.id.vp) ;
		mViewPager.setOnTouchListener(new View.OnTouchListener()
	    {
	      public boolean onTouch(View pView, MotionEvent pMotionEvent)
	      {
	    	  VIEWPAGER_ONTOUCH.set(true);
	    	  return false;
	      }
	    });
		mViewPager.setOnPageChangeListener(new GuidePageChangeListener()) ;
		mDotLayout = (ViewGroup) mRootView.findViewById(R.id.dot_ll) ;
		mErrorView = mRootView.findViewById(R.id.iv_error) ;
		mBannerService.cancel() ;
		mBannerService.get(null) ;
	}

	private void initView() {
		mNameTv = (TextView) mRootView.findViewById(R.id.tv_name) ;
		mIncomeTv = (TextView) mRootView.findViewById(R.id.tv_income) ;
		mStartMoneyBtn = (Button) mRootView.findViewById(R.id.btn_startMoney) ;
		mStartMoneyBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mActivity.getFooterMenu().switchAssets() ;
			}
		}) ;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(IndexFragments.class.getSimpleName()) ;
		if(UpdateVp!=null){
			handler.postDelayed(UpdateVp, TimeUnit.SECONDS.toMillis(5L)) ;
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(IndexFragments.class.getSimpleName()) ;
		if (handler != null) {
			handler.removeCallbacksAndMessages(null);
		}
	}
	
	private void onResponse(){
		UpdateVp = new Runnable() {
			private int currentPage;
			
			@Override
			public void run() {
				if (!VIEWPAGER_ONTOUCH.getAndSet(false)) {
					 if (mViewPager.getCurrentItem() != mViewPagerAdapter.getCount()-1) {
						 currentPage = mViewPager.getCurrentItem() + 1 ;
					 }else{
						 currentPage = 0 ;
					 }
					mViewPager.setCurrentItem(currentPage, true);
					handler.postDelayed(UpdateVp, TimeUnit.SECONDS.toMillis(5L));
				}
			}
		};
		
		handler.removeCallbacksAndMessages(null);
        handler.postDelayed(UpdateVp, TimeUnit.SECONDS.toMillis(5L));
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if(mRootView!=null){
			((ViewGroup)mRootView.getParent()).removeView(mRootView) ;
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if (handler != null) {
		     handler.removeCallbacks(UpdateVp);
		}
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (MainActivity)activity ;
	}
	
	/**
	 * 初始化广告图片 点
	 */
	private void initDotImageView(int size) {
		mDotImageViews = new ImageView[size];

		for (int i = 0; i < size; i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setLayoutParams(new LayoutParams(20, 20));
			imageView.setPadding(5, 5, 5, 5);
			mDotImageViews[i] = imageView;
			if (i == 0) {
				mDotImageViews[i].setBackgroundResource(R.drawable.banner_dian_focus);
			} else {
				mDotImageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
			}
			mDotLayout.addView(mDotImageViews[i]);
		}
	}
	
	private final class GuidePageChangeListener implements OnPageChangeListener {

		private int pageIndex;

		@Override
		public void onPageScrollStateChanged(int state) { 
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int position) {
			pageIndex = position;//%mDotImageViews.length;
			for (int i = 0; i < mDotImageViews.length; i++) {
				mDotImageViews[pageIndex%mDotImageViews.length].setBackgroundResource(R.drawable.banner_dian_focus);
				if (pageIndex%mDotImageViews.length != i) {
					mDotImageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
				}
			}

		}
	}
	
	private IOpenApiDataServiceCallback<ResponseBannerBean> mBannerCallback 
		= new IOpenApiDataServiceCallback<ResponseBannerBean>() {
		@Override
		public void onGetError(int errorCode, String errorMsg, Throwable error) {
			
		}
		
		@Override
		public void onGetData(ResponseBannerBean data) {
			if (data.isSuccess()) {
				mIconAdapter = new IconAdapter(getActivity());
				mIconAdapter.setData(data.banners);
				mViewPager.setAdapter(mIconAdapter);
				initDotImageView(data.banners.size()) ;
				mErrorView.setVisibility(View.GONE ) ;
				mViewPager.setVisibility(View.VISIBLE) ;
				onResponse() ;
			}else{
				mErrorView.setVisibility(View.VISIBLE) ;
				mViewPager.setVisibility(View.GONE) ;
			}
		}
	};

}
